package com.projecy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projecy.common.exception.BadRequestException;
import com.projecy.system.mapper.SysRoleUserMapper;
import com.projecy.system.model.SysRoleUser;
import com.projecy.system.service.SysRoleUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@RequiredArgsConstructor
public class SysRoleUserServiceImpl implements SysRoleUserService {
    @Autowired
    SysRoleUserMapper roleUserMapper;


    @Override
    public List<SysRoleUser> getRoleUserByRoleId(Long roleId) {//通过角色ID查询绑定的用户
        System.out.println("通过角色ID查询绑定的用户");
        try {
            QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            return roleUserMapper.selectList(wrapper);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    @Transactional
    public void edit(Long userId, List<String> roles) {//修改用户角色
        System.out.println("修改用户角色");
        try {
            //  首先清空该用户所有角色
            QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            roleUserMapper.delete(wrapper);
            //  然后将用户与角色绑定
            roles.forEach(role -> {
                SysRoleUser roleUser = new SysRoleUser();
                roleUser.setUserId(userId);
                roleUser.setRoleId(Long.parseLong(role));
                roleUserMapper.insert(roleUser);
            });
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    public List<SysRoleUser> getRoleUserByUserId(Long userId) {//查询当前用户角色
        try {
            QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            return roleUserMapper.selectList(wrapper);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    public void deleteByUserId(String userId) {//删除用户与角色的绑定
        try {
            LambdaQueryWrapper<SysRoleUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysRoleUser::getUserId, userId);
            roleUserMapper.delete(wrapper);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }
}
